//
//  LREmoticonToolBar.swift
//  WeiboX
//
//  Created by admin on 11/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

enum LREmoticonKeyboardBtnType: Int {
	case recent = 100
	case normal = 101
	case emoji = 102
	case lxh = 103
}

class LREmoticonToolBar: UIStackView {
	
	var callBack: ((LREmoticonKeyboardBtnType) -> ())?
	
	private lazy var lastSelectedBtn = UIButton()
	
	private lazy var btnInfoArr: [[String: Any]] = [
													["bgImgName": "compose_emotion_table_left", "title": "recent", "type": LREmoticonKeyboardBtnType.recent],
	                                                ["bgImgName": "compose_emotion_table_mid", "title": "default", "type": LREmoticonKeyboardBtnType.normal],
	                                                ["bgImgName": "compose_emotion_table_mid", "title": "emoji", "type": LREmoticonKeyboardBtnType.emoji],
	                                                ["bgImgName": "compose_emotion_table_right", "title": "lxh", "type": LREmoticonKeyboardBtnType.lxh]
	]
	
	override init(frame: CGRect) {
		super.init(frame: frame)
		
		setupUI()
	}
	
	required init(coder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setupUI() {
		
		axis = .horizontal
		distribution = .fillEqually
		
		for btnInfo in btnInfoArr {
			let title: String = btnInfo["title"] as! String
			let bgImgName: String = btnInfo["bgImgName"] as! String
			let type: LREmoticonKeyboardBtnType = btnInfo["type"] as! LREmoticonKeyboardBtnType
			
			print(title, bgImgName, type)
			addChildWidgets(title: title, bgImgName: bgImgName, type: type)
		}
	}
	
	private func addChildWidgets(title: String, bgImgName: String, type: LREmoticonKeyboardBtnType) {
		let btn = UIButton()
		
		btn.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
		
		btn.tag = type.rawValue
		btn.setTitle(title, for: .normal)
		btn.setBackgroundImage(UIImage(named: "\(bgImgName)" + "_normal"), for: .normal)
		btn.setBackgroundImage(UIImage(named: "\(bgImgName)" + "_selected"), for: .selected)
		btn.setTitleColor(.white, for: .normal)
		btn.setTitleColor(.gray, for: .selected)
		btn.titleLabel?.font = .systemFont(ofSize: 14)
		btn.adjustsImageWhenHighlighted = false
		
		addArrangedSubview(btn)
	}
	
	// 按钮事件
	@objc private func btnAction(btn: UIButton) {
		lastSelectedBtn.isSelected = false
		btn.isSelected = true
		lastSelectedBtn = btn
		
		let type = LREmoticonKeyboardBtnType(rawValue: btn.tag)!
		
		callBack?(type)
	}
	
	// 根据传入的点击选中信息设置按钮的选中状态
	func setupSelectedStatus(section: Int) {
		let btn = viewWithTag(section + 100) as! UIButton
		
		if btn == lastSelectedBtn {
			return
		}
		
		lastSelectedBtn.isSelected = false
		btn.isSelected = true
		lastSelectedBtn = btn
	}
}
